package com.china08.yxyapi.schedule.lecture;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResResourceBookContent;
import com.china08.yxyapi.entity.db.res.YxyResWeikeKnow;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack.Res;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureRes;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureRes.Knows;
import com.china08.yxyapi.entity.mg.res.YxyResQues;
import com.china08.yxyapi.model.ResModel;
import com.china08.yxyapi.model.lecture.ReqLectureKnowModel;
import com.china08.yxyapi.model.lecture.ReqLecturePrePackModel;
import com.china08.yxyapi.model.lecture.ReqLecturePrePackResModel;
import com.china08.yxyapi.model.lecture.ReqLectureResKnowModel;
import com.china08.yxyapi.model.lecture.ReqLectureResModel;
import com.china08.yxyapi.model.lecture.ReqQuesModel;
import com.china08.yxyapi.model.lecture.ReqSynLectureModel;
import com.china08.yxyapi.repository.db.YxyResResourceBookContentRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResWeikeKnowRepository;
import com.china08.yxyapi.repository.mg.YxyResQuesRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLecturePrePackRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLectureResRepository;
import com.china08.yxyapi.util.YxyScheduleRunnableUtil;

@Component
public class SynLectureTask {

    @Autowired
    public YxyLecturePrePackRepository yxyLecturePrePackRepository;

    @Autowired
    private YxyResResourceRepository yxyResResourceRepository;

    @Autowired
    private YxyResResourceBookContentRepository yxyResResourceBookContentRepository;

    @Autowired
    private YxyResWeikeKnowRepository yxyResWeikeKnowRepository;

    @Autowired
    private YxyResQuesRepository yxyResQuesRepository;

    @Autowired
    private YxyLectureResRepository yxyLectureResRepository;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.profiles.active}")
    String profiles;

    private static final Logger log = LoggerFactory.getLogger(SynLectureTask.class);

    // 备授课同步yx
    @Scheduled(fixedRate = 1000 * 60 * 10)
    public void myRanking() {

        // ##
        // 检测定时任务是否可执行
        if (!YxyScheduleRunnableUtil.checkRunnable()) { return; }

        String api = "http://localhost:9083/api_yw/comm/sync/lecture";
        if (StringUtils.equals(profiles, "pro")) {
            api = "http://www.hrbeduy.com/api_yw/comm/sync/lecture";
            log.info("北京备课包同步哈尔滨开始.....");
        } else if (StringUtils.equals(profiles, "prohrb")) {
            log.info("哈尔滨备课包同步北京开始.....");
            api = "http://yun.91yunxiao.com/api_yw/comm/sync/lecture";
        } else {
            return;
        }
        List<YxyLecturePrePack> lecturePrePacks = yxyLecturePrePackRepository.findTop1000ByIsSyncAndIsDeleteNot(false,
                1);
        if (lecturePrePacks.size() == 0) { return; }
        //
        for (YxyLecturePrePack yxyPack : lecturePrePacks) {
            log.info("同步备课包ID....." + yxyPack.getId());
            List<YxyLecturePrePack> allPack = new ArrayList<YxyLecturePrePack>();
            allPack.add(yxyPack);
            // 获取引用的备课包
            getRef(allPack, yxyPack.getReferencId());
            Collections.reverse(allPack);
            // 资源试题数据
            List<YxyResResource> reqResources = new ArrayList<YxyResResource>();
            List<YxyResResourceBookContent> reqResourceBookContents = new ArrayList<YxyResResourceBookContent>();
            List<YxyResWeikeKnow> reqWeikeKnows = new ArrayList<YxyResWeikeKnow>();
            List<ReqQuesModel> reqResQues = new ArrayList<ReqQuesModel>();
            ReqLecturePrePackModel lecturePrePackModels = new ReqLecturePrePackModel();
            List<ReqLecturePrePackResModel> lecturePrePackResModels = new ArrayList<ReqLecturePrePackResModel>();
            List<ReqLectureResModel> lectureResModels = new ArrayList<ReqLectureResModel>();
            List<ReqLectureResKnowModel> knowModels = new ArrayList<ReqLectureResKnowModel>();
            //
            for (YxyLecturePrePack yxyLecturePrePack : allPack) {
                List<Res> packRes = yxyLecturePrePack.getResources();
                for (Res res : packRes) {
                    ReqLecturePrePackResModel lecturePrePackResModel = new ReqLecturePrePackResModel();
                    BeanUtils.copyProperties(res, lecturePrePackResModel);
                    lecturePrePackResModel.setPackId(yxyLecturePrePack.getId());
                    lecturePrePackResModels.add(lecturePrePackResModel);
                    String resourceId = res.getResourceId();

                    // 资源
                    if (res.getCourseType() == 1) {
                        YxyResResource resource = yxyResResourceRepository.findById(resourceId);
                        reqResources.add(resource);
                        if (StringUtils.equals("yx14", resource.getTypeId())) {
                            // 微课
                            List<YxyResWeikeKnow> weikeKnows = yxyResWeikeKnowRepository.findByWeikeId(resourceId);
                            reqWeikeKnows.addAll(weikeKnows);
                        } else {
                            // 资源
                            List<YxyResResourceBookContent> resourceBookContents = yxyResResourceBookContentRepository
                                    .findByResourceId(resourceId);
                            reqResourceBookContents.addAll(resourceBookContents);
                        }
                    } else if (res.getCourseType() == 0) {
                        // 试题
                        YxyLectureRes lectureRes = yxyLectureResRepository.findByResourceId(resourceId);
                        List<String> quesIds = lectureRes.getQuesIds();
                        if (quesIds != null && quesIds.size() > 0) {
                            List<YxyResQues> yxyResQues = yxyResQuesRepository.findByIdIn(quesIds);
                            for (YxyResQues resQues : yxyResQues) {
                                ReqQuesModel quesModel = new ReqQuesModel();
                                BeanUtils.copyProperties(resQues, quesModel);
                                reqResQues.add(quesModel);
                            }
                        }
                        // 备课资源
                        ReqLectureResModel lectureResModel = new ReqLectureResModel();
                        BeanUtils.copyProperties(lectureRes, lectureResModel);
                        lectureResModels.add(lectureResModel);
                        // 备课知识点
                        Map<String, List<Knows>> map = lectureRes.getQuesKnows();
                        if (map != null) {
                            for (String string : map.keySet()) {
                                ReqLectureResKnowModel knowModel = new ReqLectureResKnowModel();
                                knowModel.resourceId = resourceId;
                                knowModel.quesId = string;
                                List<ReqLectureKnowModel> knowModels2 = new ArrayList<ReqLectureKnowModel>();
                                List<Knows> knows = map.get(string);
                                for (Knows knows2 : knows) {
                                    ReqLectureKnowModel knowModel2 = new ReqLectureKnowModel();
                                    knowModel2.know_id = knows2.know_id;
                                    knowModel2.know_name = knows2.know_name;
                                    knowModels2.add(knowModel2);
                                }
                                knowModel.reqLectureKnowModelMap = knowModels2;
                                knowModels.add(knowModel);
                            }
                        }
                    }
                }
                lecturePrePackModels = new ReqLecturePrePackModel();
                BeanUtils.copyProperties(yxyLecturePrePack, lecturePrePackModels);
                lecturePrePackModels.setCreatedDate(yxyLecturePrePack.getCreatedDate());
                ReqSynLectureModel model = new ReqSynLectureModel();
                model.prePack = lecturePrePackModels;
                model.prePackRess = lecturePrePackResModels;
                model.resources = reqResources;
                model.resourceBookContents = reqResourceBookContents;
                model.weikeKnows = reqWeikeKnows;
                model.resQues = reqResQues;
                model.lectureRes = lectureResModels;
                model.knowModels = knowModels;

                try {
                    ResponseEntity<ResModel> respone = restTemplate.postForEntity(api, model, ResModel.class);
                    if (respone.getBody().getEvent().equals("0")) {
                        for (YxyLecturePrePack pack : allPack) {
                            // 更新同步标识
                            pack.setIsSync(true);
                        }
                        yxyLecturePrePackRepository.save(allPack);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }

        }
        log.info("北京备课包同步哈尔滨结束.....");
    }

    public void getRef(List<YxyLecturePrePack> lecturePrePacks, String refId) {
        YxyLecturePrePack lecturePrePack = yxyLecturePrePackRepository.findById(refId);
        if (lecturePrePack != null) {
            lecturePrePacks.add(lecturePrePack);
            if (StringUtils.isNotBlank(lecturePrePack.getReferencId())) {
                getRef(lecturePrePacks, lecturePrePack.getReferencId());
            }
        }
    }

}
